package cn.com.greatwall.oauth.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import cn.com.greatwall.common.model.Result;
import cn.com.greatwall.common.utils.JsonUtil;
import cn.com.greatwall.oauth.service.impl.UnifiedLogoutService;
import cn.com.greatwall.oauth2.common.properties.SecurityProperties;
import cn.hutool.core.util.StrUtil;

/**
 * @Author herw
 * @Time 2022-01-18 09:21:18
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Resource
    private UnifiedLogoutService unifiedLogoutService;

    @Resource
    private SecurityProperties securityProperties;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        if (securityProperties.getAuth().getUnifiedLogout()) {
            unifiedLogoutService.allLogout();
        }

        String redirectUri = request.getParameter("redirect_uri");
        if (StrUtil.isNotEmpty(redirectUri)) {
            //重定向指定的地址
            redirectStrategy.sendRedirect(request, response, redirectUri);
        } else {
            response.setStatus(HttpStatus.OK.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            String jsonStr = JsonUtil.toJSONString(Result.succeed("登出成功"));
            writer.write(jsonStr);
            writer.flush();
        }
    }
}
